<template>
  <div class="second-hand-order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索订单记录"
        style="width: 300px"
        clearable
      >
        <template #prefix>
          <span style="margin-right: 8px">🔍</span>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <span style="margin-right: 5px">+</span>新增订单记录
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredOrders" border style="width: 100%">
      <el-table-column prop="orderId" label="订单编号" width="180" sortable />
      <el-table-column prop="buyerName" label="买家姓名" width="120" />
      <el-table-column prop="sellerName" label="卖家姓名" width="120" />
      <el-table-column prop="productName" label="商品名称" width="180" />
      <el-table-column prop="orderDate" label="订单日期" width="180">
        <template #default="{ row }">
          {{ formatDate(row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单总金额" width="120" sortable />
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusType[row.status]">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.orderId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑订单记录' : '新增订单记录'"
      width="600"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="formData.orderId" :disabled="isEditMode" />
        </el-form-item>
        <el-form-item label="买家姓名" prop="buyerName">
          <el-input v-model="formData.buyerName" />
        </el-form-item>
        <el-form-item label="卖家姓名" prop="sellerName">
          <el-input v-model="formData.sellerName" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker
            v-model="formData.orderDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input-number
            v-model="formData.totalAmount"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')
}

// 状态选项配置
const statusOptions = [
  { value: 0, label: '待付款' },
  { value: 1, label: '已付款' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已取消' }
]
const statusType = {
  0: 'warning',
  1: 'success',
  2: 'info',
  3: 'success',
  4: 'danger'
}

// 10 个二手订单的测试数据
const orders = ref([
  {
    orderId: 'OD001',
    buyerName: '张三',
    sellerName: '李四',
    productName: '二手手机',
    orderDate: '2024-04-01',
    totalAmount: 1500,
    status: 1
  },
  {
    orderId: 'OD002',
    buyerName: '王五',
    sellerName: '赵六',
    productName: '二手自行车',
    orderDate: '2024-04-02',
    totalAmount: 300,
    status: 0
  },
  {
    orderId: 'OD003',
    buyerName: '孙七',
    sellerName: '周八',
    productName: '二手笔记本电脑',
    orderDate: '2024-04-03',
    totalAmount: 2000,
    status: 2
  },
  {
    orderId: 'OD004',
    buyerName: '吴九',
    sellerName: '郑十',
    productName: '二手相机',
    orderDate: '2024-04-04',
    totalAmount: 2500,
    status: 3
  },
  {
    orderId: 'OD005',
    buyerName: '王十一',
    sellerName: '李十二',
    productName: '二手沙发',
    orderDate: '2024-04-05',
    totalAmount: 800,
    status: 4
  },
  {
    orderId: 'OD006',
    buyerName: '张十三',
    sellerName: '刘十四',
    productName: '二手书籍',
    orderDate: '2024-04-06',
    totalAmount: 100,
    status: 0
  },
  {
    orderId: 'OD007',
    buyerName: '陈十五',
    sellerName: '杨十六',
    productName: '二手冰箱',
    orderDate: '2024-04-07',
    totalAmount: 1200,
    status: 1
  },
  {
    orderId: 'OD008',
    buyerName: '黄十七',
    sellerName: '林十八',
    productName: '二手空调',
    orderDate: '2024-04-08',
    totalAmount: 1800,
    status: 2
  },
  {
    orderId: 'OD009',
    buyerName: '何十九',
    sellerName: '郭二十',
    productName: '二手电动车',
    orderDate: '2024-04-09',
    totalAmount: 600,
    status: 3
  },
  {
    orderId: 'OD010',
    buyerName: '罗二十一',
    sellerName: '梁二十二',
    productName: '二手桌椅',
    orderDate: '2024-04-10',
    totalAmount: 400,
    status: 4
  }
])

// 搜索功能
const searchText = ref('')
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    return Object.values(order).some(value =>
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
    )
  })
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  orderId: null,
  buyerName: '',
  sellerName: '',
  productName: '',
  orderDate: new Date().toISOString().split('T')[0],
  totalAmount: 0,
  status: 0
})

// 表单验证规则
const formRules = {
  orderId: [{ required: true, message: '请输入订单编号', trigger: 'blur' }],
  buyerName: [{ required: true, message: '请输入买家姓名', trigger: 'blur' }],
  sellerName: [{ required: true, message: '请输入卖家姓名', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  orderDate: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
  totalAmount: [{ required: true, message: '请输入订单总金额', trigger: 'blur' }],
  status: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (orderId) => {
  ElMessageBox.confirm('确定要删除该订单记录吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(o => o.orderId !== orderId)
    ElMessage.success('删除成功')
  })
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = orders.value.findIndex(o => o.orderId === formData.orderId)
    orders.value.splice(index, 1, { ...formData })
  } else {
    orders.value.push({
      ...formData,
      orderId: `OD${Date.now()}`
    })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
}

// 重置表单
const resetForm = () => {
  formData.orderId = null
  formData.buyerName = ''
  formData.sellerName = ''
  formData.productName = ''
  formData.orderDate = new Date().toISOString().split('T')[0]
  formData.totalAmount = 0
  formData.status = 0
}
</script>

<style scoped>
.second-hand-order-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  font-weight: 500;
}
</style>
    